angular.module('mycontrollers', ['ionic']).factory('Name', [function() {
    return {
        name: "who",
        objId: "",
        friend: "",
        friendId: "",
        icon: "shequ1.gif"
    };
}]).controller('ContentController', function($scope, $ionicSideMenuDelegate) {
    $scope.toggleLeft = function() {
        $ionicSideMenuDelegate.toggleLeft();
    };
}).controller('ListCtrl', function($scope, $ionicPopup, $timeout, $location) {
    $scope.shouldShowDelete = false;
    $scope.shouldShowReorder = false;
    $scope.listCanSwipe = true;
    $scope.items = [];
    var Room = Bmob.Object.extend("Room");
    var room = new Bmob.Query(Room);
    room.find({
        success: function(results) {
            // 循环处理查询到的数据
            for (var i = 0; i < results.length; i++) {
                var object = results[i];
                var isShowRes;
                pepole = object.get('pepole');
                if (pepole == 6) {
                    isShowRes = true;
                } else {
                    isShowRes = false;
                }
                var str = {
                    roomId: object.get('roomId'),
                    roomName: object.get('roomName'),
                    pepole: object.get('pepole'),
                    isShow: isShowRes
                };
                $scope.items.push(str);
            }
        },
        error: function(error) {
            alert("查询房间失败: " + error.code + " " + error.message);
        }
    });
    $scope.playing = function(me) {
        //console.log(me);
        $location.path('/play');
    };
    $scope.loadMore = function() {
        var Room = Bmob.Object.extend("Room");
        var query = new Bmob.Query(Room);
        // 跳过前items条数据查询
        query.skip($scope.items.length);
        // 查询所有数据
        query.find({
            success: function(results) {
                // 循环处理查询到的数据
                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    var isShowRes;
                    pepole = object.get('pepole');
                    if (pepole == 6) {
                        isShowRes = true;
                    } else {
                        isShowRes = false;
                    }
                    var str = {
                        roomId: object.get('roomId'),
                        roomName: object.get('roomName'),
                        pepole: object.get('pepole'),
                        isShow: isShowRes
                    };
                    $scope.items.push(str);
                }
            },
            error: function(error) {
                alert("查询房间失败: " + error.code + " " + error.message);
            }
        });
    };
    //一个弹出创建房间的东东~
    $scope.showPopup = function() {
        $scope.data = {};
        var popUp = $ionicPopup.show({
            template: '<input type="text" ng-model="data.roomName">',
            title: '创建一个牛逼哄哄的房间名',
            scope: $scope,
            buttons: [{ //放在弹窗footer内的按钮。
                text: '取消',
                type: 'button-default',
            }, {
                text: '确定',
                type: 'button-light',
                onTap: function(e) {
                    // 返回的值会导致处理给定的值。
                    if (!$scope.data.roomName) {
                        e.preventDefault();
                    } else {
                        return $scope.data.roomName;
                    }
                }
            }]
        });
        // $timeout(function() {
        //    myPopup.close(); //由于某种原因3秒后关闭弹出
        // }, 3000)
        popUp.then(function(res) {
            var Room = Bmob.Object.extend("Room");
            var room = new Room();
            room.set("roomName", res);
            room.set("pepole", 1);
            var num = getRandom();
            var res = checkRoomId(num);
            while (!res) {
                num = getRandom();
                res = checkRoomId(num);
            }
            room.set("roomId", num);
            room.save(null, {
                success: function(room) {
                    //跳转房间
                    $location.path('/play');
                },
                error: function(room, error) {
                    // 添加失败
                    alert('添加数据失败，返回错误信息：' + error.description);
                }
            });
        });
    };

    function checkRoomId(number) {
        var res = true;
        var Room = new Bmob.Object.extend("Room");
        var room = new Bmob.Query(Room);
        room.find({
            success: function(results) {
                // 循环处理查询到的数据
                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    if (number == object.get('roomId')) {
                        res = false;
                    }
                }
            },
            error: function(error) {
                alert("查询失败: " + error.code + " " + error.message);
            }
        });
        return res;
    };

    function getRandom() {
        var number = parseInt(Math.random() * 1000);
        if (number.length == 1) {
            number = "00" + number;
        } else if (number.length == 2) {
            number = "0" + number;
        } else {
            number = number;
        }
        return number;
    };
}).controller('registerCtrl', ['$scope', '$location', '$ionicPopup', '$timeout', function($scope, $location, $ionicPopup, $timeout) {
    $scope.username = "";
    $scope.passwd = "";
    $scope.register = function() {
        if ($scope.username == null || $scope.username.length == 0 || $scope.passwd == null || $scope.passwd.length == 0) {
            showAlert("提示", "账号密码不能为空！");
            return;
        } else {
            //console.log(checkUsername($scope.username));
            //TODO $scope.name  equal  check username from db 
            if (true) {
                var WhoUser = Bmob.Object.extend("WhoUser");
                var user = new WhoUser();
                user.set("username", $scope.username);
                user.set("password", $scope.passwd);
                user.set("exp", 1);
                user.set("sex", "男");
                user.set("sign", "Who are you??");
                user.set("wechat", "xxx-xx");
                user.save(null, {
                    success: function(object) {
                        $location.path('/login');
                    },
                    error: function(model, error) {
                        alert("create object fail");
                    }
                });
            } else {
                showAlert("提示", "账号已存在！！");
            }
        };

        function checkUsername(name) {
            var WhoUser = Bmob.Object.extend("WhoUser");
            var query = new Bmob.Query(WhoUser);
            var tag = new Boolean(true);
            // 查询所有数据
            query.find({
                success: function(results) {
                    // 循环处理查询到的数据
                    for (var i = 0; i < results.length; i++) {
                        var object = results[i];
                        if (name == object.get('username')) {
                            tag = false;
                        }
                    }
                    // console.log(tag);
                    return tag;
                },
                error: function(error) {
                    console.log("查询失败: " + error.code + " " + error.message);
                }
            });
        }
    };

    function showAlert(titleStr, templateStr) {
        var alertPopup = $ionicPopup.alert({
            title: titleStr,
            template: templateStr
        });
        alertPopup.then(function(res) {
            console.log('Thank you for not eating my delicious ice cream cone');
        });
        $timeout(function() {
            alertPopup.close(); //close the popup after 3 seconds for some reason
        }, 2000);
    };
}]).controller('loginCtrl', ['$scope', '$location', 'Name', '$ionicPopup', '$timeout', function($scope, $location, Name, $ionicPopup, $timeout) {
    $scope.username = "";
    $scope.passwd = "";
    $scope.goin = function() {
        if ($scope.username == null || $scope.username.length == 0 || $scope.passwd == null || $scope.passwd.length == 0) {
            showAlert("提醒", "密码或账号不能为空");
            return;
        } else {
            //console.log($scope.username + "");
            var WhoUser = Bmob.Object.extend("WhoUser");
            var query = new Bmob.Query(WhoUser);
            query.equalTo("username", $scope.username);
            query.find({
                success: function(results) {
                    if (results.length != 0) {
                        var object = results[0];
                        if ($scope.passwd == object.get('password')) {
                            Name.name = $scope.username;
                            //console.log(Name.name);
                            $location.path('/goin');
                        } else {
                            showAlert('提醒', '账号或密码错误');
                        }
                    };
                },
                error: function(error) {
                    console.log(error);
                }
            });
        }
    };

    function showAlert(titleStr, templateStr) {
        var alertPopup = $ionicPopup.alert({
            title: titleStr,
            template: templateStr,
            type: 'button-light'
        });
        alertPopup.then(function(res) {
            console.log('Thank you for not eating my delicious ice cream cone');
        });
        $timeout(function() {
            alertPopup.close(); //close the popup after 3 seconds for some reason
        }, 2000);
    }
}]).controller('loadUserInfoCtrl', ['$scope', 'Name', '$ionicPopup', function($scope, Name, $ionicPopup) {
    //console.log(Name.name);
    $scope.username = "";
    $scope.exp = "";
    $scope.sign = "";
    var WhoUser = Bmob.Object.extend("WhoUser");
    var query = new Bmob.Query(WhoUser);
    query.equalTo("username", Name.name);
    query.find({
        success: function(results) {
            var user = results[0];
            $scope.username = Name.name;
            $scope.exp = user.get('exp');
            $scope.sign = user.get('sign');
            Name.objId = user.id;
        },
        error: function(error) {
            alert('异常错误');
        }
    });
    $scope.showPopup = function() {
        $scope.data = {}
        var myPopup = $ionicPopup.show({
            template: '<input type="text" ng-model="data.sign">',
            title: '输入你的个性签名',
            subTitle: '随便写点啥~',
            scope: $scope,
            buttons: [{
                text: '取消'
            }, {
                text: '<b>保存</b>',
                type: 'button-light',
                onTap: function(e) {
                    if (!$scope.data.sign) {
                        //don't allow the user to close unless he enters wifi password
                        e.preventDefault();
                    } else {
                        return $scope.data.sign;
                    }
                }
            }]
        });
        myPopup.then(function(res) {
            var WhoUser = Bmob.Object.extend("WhoUser");
            var who = new WhoUser();
            query.get(Name.objId, {
                success: function(obj) {
                    obj.set('sign', res);
                    obj.save();
                    $scope.sign = res;
                },
                error: function(object, error) {
                    console.log(error);
                }
            });
        });
    };
}]).controller('friendListCtrl', function($scope, Name, $location, $ionicPopup, $timeout) {
    $scope.shouldShowDelete = false;
    $scope.shouldShowReorder = false;
    $scope.listCanSwipe = true;
    $scope.items = [];
    var WhoUser = Bmob.Object.extend("WhoUser");
    var query = new Bmob.Query(WhoUser);
    query.find({
        success: function(results) {
            for (var i = 0; i < results.length; i++) {
                var user = results[i]
                var name = user.get('username');
                var exp = user.get('exp');
                var sign = user.get('sign');
                var level = 0;
                if (exp >= 1000) {
                    level = Math.ceil(exp / 1000);
                }
                if (name != Name.name && checkMyFriend(name)) {
                    $scope.items.push({
                        username: name,
                        exp: exp,
                        sign: sign,
                        level: level
                    });
                }
            }
        },
        error: function(error) {
            alert('异常错误');
        }
    });

    function checkMyFriend(friendName) {
        // TODO check your friend list from your db
        return true;
    };
    $scope.info = function(friend) {
        //console.log(friend);
        Name.friend = friend.username;
        //console.log(Name.friend);
        if (Name.friend != null) {
            $location.path("/friendinfo");
        } else {
            var alertPopup = $ionicPopup.alert({
                title: '用户不存在',
                template: '神秘事件之消失的黑衣人'
            });
            alertPopup.then(function(res) {
                console.log('Thank you for not eating my delicious ice cream cone');
            });
        }
    };
}).controller('yourFriendCtrl', ['$scope', function($scope) {
    //TODO loading your friends from bmob
}]).controller('friendInfoCtrl', ['$scope', 'Name', function($scope, Name) {
    $scope.username = "";
    $scope.sign = "";
    $scope.wechat = "";
    $scope.sex = "";
    $scope.habit = "";
    var WhoUser = Bmob.Object.extend("WhoUser");
    var query = new Bmob.Query(WhoUser);
    query.equalTo("username", Name.friend);
    query.find({
        success: function(results) {
            var user = results[0];
            $scope.username = Name.friend;
            $scope.sign = user.get('sign');
            $scope.wechat = user.get('wechat');
            $scope.sex = user.get('sex');
            Name.friendId = user.id;
            //console.log(Name.objId);
        },
        error: function(error) {
            alert('异常错误');
        }
    });
    $scope.addFriend = function() {
        var user = Bmob.Object.createWithoutData("WhoUser", Name.friendId);
        var Friends = Bmob.Object.extend("Friends");
        var friend = new Friends();
        friend.set("name", Name.friend);
        friend.set("user", user);
        friend.save();
    };
}]).controller('settoselfCtrl', ['$scope', 'Name', '$ionicPopup', '$location', function($scope, Name, $ionicPopup, $location) {
    $scope.sign = "";
    $scope.sex = "";
    $scope.wechat = "";
    $scope.isActiveMale = true;
    $scope.isActiveFemale = true;
    $scope.isActiveSimon = true;
    $scope.isActiveLily = true;
    $scope.isActiveGay = true;
    $scope.icon = Name.icon;
    var tag = new Boolean(false);
    var WhoUser = Bmob.Object.extend("WhoUser");
    //创建查询对象，入口参数是对象类的实例
    var query = new Bmob.Query(WhoUser);
    //查询单条数据，第一个参数是这条数据的objectId值
    query.get(Name.objId, {
        success: function(object) {
            // 查询成功，调用get方法获取对应属性的值
            $scope.sign = object.get("sign");
            $scope.sex = object.get("sex");
            $scope.wechat = object.get("wechat");
            if ($scope.sex != null) {
                switch ($scope.sex) {
                    case "男":
                        $scope.isActiveMale = false;
                        break;
                    case "女":
                        $scope.isActiveFemale = false;
                        break;
                    case "GAY":
                        $scope.isActiveGay = false;
                        break;
                    case "百合":
                        $scope.isActiveLily = false;
                        break;
                    case "人妖":
                        $scope.isActiveSimon = false;
                        break;
                }
            };
        },
        error: function(object, error) {
            // 查询失败
        }
    });
    $scope.toUpdate = function() {
        if ($scope.sign != "" && $scope.sex != "" && $scope.wechat != "") {
            toServer();
        } else {
            var confirmPopup = $ionicPopup.confirm({
                title: '未完成资料',
                template: '确认要更改吗？'
            });
            confirmPopup.then(function(res) {
                if (res) {
                    toServer();
                    console.log("here3");
                } else {
                    console.log('you click cancel');
                }
            });
        }

        function toServer() {
            var WhoUser = Bmob.Object.extend("WhoUser");
            var who = new Bmob.Query(WhoUser);
            who.get(Name.objId, {
                success: function(object) {
                    object.set('sign', $scope.sign);
                    object.set('sex', $scope.wechat);
                    object.set('wechat', $scope.wechat);
                    object.save(null, {
                        success: function(objectUpdate) {
                            $location.path('/goin');
                            console.log("create object success, object score:" + objectUpdate.get("score"));
                        },
                        error: function(model, error) {
                            console.log("create object fail");
                        }
                    });
                },
                error: function(object, error) {
                    console.log(error);
                }
            });
        }
    };
    $scope.male = function() {
        checkTag("male");
    };
    $scope.female = function() {
        checkTag("female");
    };
    $scope.gay = function() {
        checkTag("gay");
    };
    $scope.simon = function() {
        checkTag("simon");
    };
    $scope.lily = function() {
        checkTag("lily");
    };

    function checkTag(str) {
        switch (str) {
            case "male":
                checkMale();
                break;
            case "female":
                checkFemale();
                break;
            case "gay":
                checkGay();
                break;
            case "simon":
                checkSimon();
                break;
            case "lily":
                checkLily();
                break;
        }
    }

    function checkMale() {
        $scope.isActiveMale = true;
        $scope.isActiveFemale = true;
        $scope.isActiveSimon = true;
        $scope.isActiveLily = true;
        $scope.isActiveGay = true;
        if (!tag) {
            tag = true;
            $scope.isActiveMale = false;
            $scope.sex = "男";
        } else {
            tag = false;
            $scope.isActiveMale = true;
            $scope.sex = "";
        }
    }

    function checkFemale() {
        $scope.isActiveMale = true;
        $scope.isActiveFemale = true;
        $scope.isActiveSimon = true;
        $scope.isActiveLily = true;
        $scope.isActiveGay = true;
        if (!tag) {
            tag = true;
            $scope.isActiveFemale = false;
            $scope.sex = "女";
        } else {
            tag = false;
            $scope.isActiveFemale = true;
            $scope.sex = "";
        }
    }

    function checkGay() {
        $scope.isActiveMale = true;
        $scope.isActiveFemale = true;
        $scope.isActiveSimon = true;
        $scope.isActiveLily = true;
        $scope.isActiveGay = true;
        if (!tag) {
            tag = true;
            $scope.isActiveGay = false;
            $scope.sex = "GAY";
        } else {
            tag = false;
            $scope.isActiveGay = true;
            $scope.sex = "";
        }
    }

    function checkSimon() {
        $scope.isActiveMale = true;
        $scope.isActiveFemale = true;
        $scope.isActiveSimon = true;
        $scope.isActiveLily = true;
        $scope.isActiveGay = true;
        if (!tag) {
            tag = true;
            $scope.isActiveSimon = false;
            $scope.sex = "人妖";
        } else {
            tag = false;
            $scope.isActiveSimon = true;
            $scope.sex = "";
        }
    }

    function checkLily() {
        $scope.isActiveMale = true;
        $scope.isActiveFemale = true;
        $scope.isActiveSimon = true;
        $scope.isActiveLily = true;
        $scope.isActiveGay = true;
        if (!tag) {
            tag = true;
            $scope.isActiveLily = false;
            $scope.sex = "百合";
        } else {
            tag = false;
            $scope.isActiveLily = true;
            $scope.sex = "";
        }
    }
}]).controller('iconInfoCtrl', ['$scope', 'Name', '$location', function($scope, Name, $location) {
    $scope.items = [{
        A: '1',
        B: '2',
        C: '3',
        M: '50px'
    }, {
        A: '4',
        B: '5',
        C: '6',
        M: '0px'
    }, {
        A: '7',
        B: '8',
        C: '9',
        M: '0px'
    }, {
        A: '10',
        B: '11',
        C: '12',
        M: '0px'
    }];
    $scope.iconClick = function(i) {
        Name.icon = "a" + i + ".jpg";
        console.log(Name.icon);
        $location.path('/settoself');
    };
}]);